import $ from 'jquery';

import './workflow.less';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import axios from 'axios';
import diagramXML from './newDiagram.bpmn';
import Keycloak from 'keycloak-js';

//var FormData = require('form-data');

import {
  BpmnPropertiesPanelModule,
  BpmnPropertiesProviderModule,
  CamundaPlatformPropertiesProviderModule
} from 'bpmn-js-properties-panel';

import CamundaBpmnModdle from 'camunda-bpmn-moddle/resources/camunda.json';
import customTranslate from './customTranslate/customTranslate';

const baseurl = 'http://localhost/camunda';
var token;

function initKeycloak() {
  const keycloak = new Keycloak();
  console.log('set keycloak');
  keycloak.init({onLoad: 'login-required'}).then(function(authenticated) {
      alert(authenticated ? 'authenticated' : 'not authenticated');
      if (authenticated) {
        console.log(keycloak.token);
        token = keycloak.token;
      }
  }).catch(function() {
      alert('failed to initialize');
  });
}

$('body').on('load', initKeycloak());

var container = $('#js-drop-zone');
var customTranslateModule = {
  translate: [ 'value', customTranslate ]
};

var modeler = new BpmnModeler({
  container: '#js-canvas',
  propertiesPanel: {
    parent: '#js-properties-panel'
  },
  additionalModules: [
    BpmnPropertiesPanelModule,
    BpmnPropertiesProviderModule,
    CamundaPlatformPropertiesProviderModule,
    customTranslateModule
  ],
  moddleExtensions: {
    camunda: CamundaBpmnModdle
  }
});

// Deployment button
$('#js-deployment').on("click", async function(event){
  const { xml } = await modeler.saveXML({ format: true });
  console.log(xml);
  const parser = new DOMParser();
  const xmldoc = parser.parseFromString(xml, "application/xml");
  const processes = xmldoc.getElementsByTagName('bpmn2:process');
  const process_name = processes[0].getAttribute('name');
  const process_id = processes[0].getAttribute('id');
  const encode_data = encodeURIComponent(xml);
  const file = new File([xml], "diagram.bpmn", {type: "text/plain"});
  const { svg } = await modeler.saveSVG();
  const img_file = new File([svg], "diagram.svg", {type: "image/svg+xml"});
  const data = new FormData();
  data.append("deployment-name", process_name);
  data.append("deployment-source", "process application");
  data.append("data", file);
  data.append("diagram", img_file);
  axios.create({withCredentials: true}).post(
    baseurl+'/engine-rest/deployment/create', 
    data, 
    {headers: {'Content-Type':'multipart/form-data', 'Authorization': 'Bearer '+token}}
    ).then(
      res=>{
        console.log('res=>', res);
        if (res.status==200) {
          alert("部署成功，点击链接查看:"+res.data.links[0].href);
        }
        console.log(res.status);
        console.log(res.data.links[0].href);
      }
    )
})

function createNewDiagram() {
  openDiagram(diagramXML);
}

async function openDiagram(xml) {

  try {

    await modeler.importXML(xml);

    container
      .removeClass('with-error')
      .addClass('with-diagram');
  } catch (err) {

    container
      .removeClass('with-diagram')
      .addClass('with-error');

    container.find('.error pre').text(err.message);

    console.error(err);
  }
}

function registerFileDrop(container, callback) {

  function handleFileSelect(e) {
    e.stopPropagation();
    e.preventDefault();
    var files = e.dataTransfer.files;

    var file = files[0];

    var reader = new FileReader();

    reader.onload = function(e) {

      var xml = e.target.result;

      callback(xml);
    };

    reader.readAsText(file);
  }

  function handleDragOver(e) {
    e.stopPropagation();
    e.preventDefault();

    e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
  }

  container.get(0).addEventListener('dragover', handleDragOver, false);
  container.get(0).addEventListener('drop', handleFileSelect, false);
}


// file drag / drop ///////////////////////

// check file api availability
if (!window.FileList || !window.FileReader) {
  window.alert(
    'Looks like you use an older browser that does not support drag and drop. ' +
    'Try using Chrome, Firefox or the Internet Explorer > 10.');
} else {
  registerFileDrop(container, openDiagram);
  console.log("registered");
}

// bootstrap diagram functions

$(function() {

  $('#js-create-diagram').click(function(e) {
    e.stopPropagation();
    e.preventDefault();

    createNewDiagram();
  });

  var downloadLink = $('#js-download-diagram');
  var downloadSvgLink = $('#js-download-svg');

  $('.buttons a').click(function(e) {
    if (!$(this).is('.active')) {
      e.preventDefault();
      e.stopPropagation();
    }
  });

  function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
      link.addClass('active').attr({
        'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
        'download': name
      });
    } else {
      link.removeClass('active');
    }
  }

  var exportArtifacts = debounce(async function() {

    try {

      const { svg } = await modeler.saveSVG();

      setEncoded(downloadSvgLink, 'diagram.svg', svg);
    } catch (err) {

      console.error('Error happened saving svg: ', err);
      setEncoded(downloadSvgLink, 'diagram.svg', null);
    }

    try {

      const { xml } = await modeler.saveXML({ format: true });
      setEncoded(downloadLink, 'diagram.bpmn', xml);
    } catch (err) {

      console.error('Error happened saving XML: ', err);
      setEncoded(downloadLink, 'diagram.bpmn', null);
    }
  }, 500);

  modeler.on('commandStack.changed', exportArtifacts);
});



// helpers //////////////////////

function debounce(fn, timeout) {

  var timer;

  return function() {
    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(fn, timeout);
  };
}